<!--
 * @FilePath     : /study_code/layui/12-7-3.html
 * @Description  : 如何获取一组复选框的值
 * @Date         : 2025-04-07 16:07:21
 * @Author       : Fang YingGui
 * @LastEditors  : fangyinggui 18715384437@163.com
 * @LastEditTime : 2025-04-07 17:01:21
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>documentName</title>
    <link rel="stylesheet" href="/layui/dist/css/layui.css" />
  </head>
  <body>
    <h2>类型选中：</h2>
    <form class="layui-form">
      <div class="layui-form-item">
        <label class="layui-form-label">吃饭</label>
        <div class="layui-input-block">
          <input type="checkbox" name="type" class="layui-input" value="1" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">喝酒</label>
        <div class="layui-input-block">
          <input type="checkbox" name="type" class="layui-input" value="2" />
        </div>
      </div>
    </form>

    <button id="btn1">获取一组表单的选中值</button>

    <script src="/layui/dist/layui.js"></script>
    <script>
      layui.use(function () {
        var $ = layui.$
        var form = layui.form
        var layer = layui.layer

        /**
         * @brief: 获取 layui 一组复选框的选中值s
         * @param {*} source: 表单的 name 属性
         * @return {array} 返回复选框，选中 value 值的 数组
         * tip: 无 value 值时，返回的是 'on' 字符
         */
        function checkboxData(source) {
          var arr = []
          $('input[name=' + source + ']:checked').each(function () {
            arr.push($(this).val())
          })
          /*if(arr.length==0){
              layer.msg("必选项不能为空",{icon: 5})
          }*/
          return arr.join(',')
        }

        $('#btn1').on('click', function () {
          var result = checkboxData('type')
          console.log('获取复选框组的值', result)
        })
      })
    </script>
  </body>
</html>
